<?php
/**
 * Created by PhpStorm.
 * User: Rei
 * Date: 16/5/2
 * Time: 21:54
 * Mail: rei@king.moe
 */

namespace Home\Model;

use Think\Model;

class UserModel extends Model
{

    // 用户登陆
    public function signIn($data){
        $checked = $this->checkUser($data);
        if($checked){
            if($this->createUserToken($checked['uid'])){
                $this->updateLogTime($checked['uid']);
                return true;
            }
        }
        return false;
    }

    //更新登陆时间
    public function updateLogTime($uid){
        return $this->data(array( 'uid'=>$uid, 'logintime'=>time() ))->save();
    }

    // 验证用户名和密码
    public function checkUser($data){
        $checked = $this->where($data)->field('uid')->find();
        if($checked){
            return $checked;
        }else{
            return false;
        }
    }

    //    添加用户
    public function addUser($data){
        $userid = $this->add($data);
        if($userid){
            return $userid;
        }else{
            return false;
        }
    }

    //检测未注册邮箱
    public function checkMail($mail){
        $used = $this->where(array("email" => $mail))->find();
        if(!$used){
            return true; //未使用
        }else{
            return false; //已使用
        }
    }

    //检查邮箱验证Token
    public function verifyMailToken($uid, $email, $token){
        $verified = $this->where(array('uid'=>$uid, 'regtoken'=>$token, 'email'=>$email))->find();
        if($verified){
            //更新
            $this->where(array('uid'=>$uid))->data(array("exptime"=>1))->save();
            return true;
        }
        return false;
    }

    //生成登陆Token
    public function createUserToken($uid){
        $salt = C('TOKEN_SALT');
        $token = md5($uid.time().$salt);
        $result = $this->data(array('usrtoken'=>$token))->where(array('uid'=>$uid))->save();
        if($result){
            cookie('islogin',$token,3600*24*7); // cookie保存1周
            session('uid', $uid); //保存session
            return true;
        }
        return false;
    }

    //获取token
    public function getUserToken($uid){
        $token = $this->where(array('uid'=>$uid))->field('usrtoken')->find();
        if($token){
            return $token['usrtoken'];
        }else{
            return false;
        }
    }

    //检测登陆Token 返回验证成功的uid
    public function verifyUserToken($token){
        $verified = $this->where(array('usrtoken'=>$token))->field('uid')->find();
        if($verified){
            return $verified['uid'];
        }
        return false;
    }

    //获取用户登录信息
    public function getUser(){
        $data = array();
        if(session('?uid')){
            $uid = session('uid');
            $data = $this->field('uid, avatar, username')->where(array('uid'=>$uid))->find();
        }

        return $data;
    }
}